import React, { useState } from 'react';
import { Button, Spin, Alert, Form, Input } from 'dingtalk-design-desktop';



const FetchExample2: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [formData, setFormData] = useState<LoginData>({ username: '', password: '' });

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 发送POST请求登录
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    
    try {
      // 发送POST请求
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // 如果需要发送cookie，设置credentials为'include'
          // 注意：目标服务器需要设置相应的CORS头
        },
        // 如果需要包含cookie
        credentials: 'include', // 包含跨域请求的cookie
        body: JSON.stringify({
          title: '登录请求',
          body: `用户名: ${formData.username}, 密码: ${formData.password}`,
          userId: 1,
        })
      });
      
      // 检查响应是否成功
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      
      // 解析 JSON 数据
      const data = await response.json();
      console.log('登录响应:', data);
      
      // 模拟设置用户信息
      setUser({
        id: data.id,
        name: formData.username,
        email: `${formData.username}@example.com`
      });
      
      // 重置表单
      setFormData({ username: '', password: '' });
    } catch (err) {
      // 处理错误
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      console.error('登录错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 退出登录
  const handleLogout = () => {
    setUser(null);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '500px', margin: '0 auto' }}>
      <h2>Fetch POST 请求示例</h2>
      <p>演示发送POST请求、处理跨域、设置cookie和获取数据</p>
      
      {!user ? (
        <Form onFinish={handleLogin}>
          <Form.Item label="用户名">
            <Input
              name="username"
              value={formData.username}
              onChange={handleInputChange}
              placeholder="请输入用户名"
              required
            />
          </Form.Item>
          
          <Form.Item label="密码">
            <Input
              type="password"
              name="password"
              value={formData.password}
              onChange={handleInputChange}
              placeholder="请输入密码"
              required
            />
          </Form.Item>
          
          <Form.Item>
            <Button   onClick={handleLogin}
              type="primary" 
              htmlType="submit"
              loading={loading}
              disabled={loading}
            >
              {loading ? '登录中...' : '登录'}
            </Button>
          </Form.Item>
        </Form>
      ) : (
        <div>
          <Alert 
            type="success" 
            message="登录成功" 
            description={`欢迎, ${user.name}!`} 
          />
          <div style={{ marginTop: '16px' }}>
            <p><strong>用户ID:</strong> {user.id}</p>
            <p><strong>用户名:</strong> {user.name}</p>
            <p><strong>邮箱:</strong> {user.email}</p>
          </div>
          <Button 
            type="default" 
            onClick={handleLogout}
            style={{ marginTop: '16px' }}
          >
            退出登录
          </Button>
        </div>
      )}
      
      {/* 错误提示 */}
      {error && (
        <Alert 
          type="error" 
          message="错误" 
          description={error} 
          closable 
          onClose={() => setError(null)} 
          style={{ marginTop: '16px' }}
        />
      )}
      
      <div style={{ marginTop: '24px', padding: '16px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
        <h3>说明:</h3>
        <ul>
          <li>此示例演示了如何发送POST请求</li>
          <li>使用<code>credentials: 'include'</code>包含跨域cookie</li>
          <li>设置适当的请求头</li>
          <li>处理响应和错误</li>
        </ul>
        <p><strong>注意:</strong> 由于跨域限制，实际请求可能被阻止。在生产环境中，服务器需要正确配置CORS头。</p>
      </div>
    </div>
  );
};

export default FetchExample2;